/**
 * 
 */

var updateTime = 10000;
$(document).ready(function() {

	updateProgressbar();
	
	updateTorrents();
	
	//$('.file_list').toggle(false);
	$( ".files_header" ).button();
	
	
	$( ".files_header" ).live('click',displayFileList);
});


function updateTorrents(){
	$.ajax({
		
		url : "/OnlineMedia/getTorrents.action",
		data : "id=1",
		type : "post",
		cache: false,
	    timeout: updateTime,
	    success : displayTorrents,
		error : handleError,
		complete : function(XMLHttpRequest) {
			setTimeout(updateTorrents, updateTime);
		}
	});
}

function updateProgressbar(){
	$(".progressbar").each(function(index, element) {
		var ele = element;
		var value = parseInt($(element).attr('value'));
		$(element).progressbar({
			value : value
		});
	});
}

function displayFileList(event){
	var id = $(event.currentTarget).attr('id');
	$('#file_list_'+id).slideToggle();
}

function parseJsonFiles(json) {
	var obj = $.parseJSON(json);
	if (obj == null) {
		obj = json;
	}
	return obj;
}


function displayTorrents(json) {
	var obj = parseJsonFiles(json);
	var torrentList = obj.torrentList;
	$(torrentList).each(function(index,element) {
		var id = element.id;
		var percentDone = element.percentDone;
		
		$("progressbar_"+id).attr('value',percentDone);
	});
	
	updateProgressbar();
}

function handleError(XMLHttpRequest, textStatus, errorThrown) {
	alert("Error while requesting server");
}